<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>组件间通信</title>
</head>
<body>
<!-- 通信可分为父子组件之间的通信,兄弟组件通信,跨级组件之间的通信 -->
<!-- 自定义事件 -->
<div id="cus_event">
    <p>总数:{{ total }}</p>
    <cus-event-component :count="total" @increase="handleGetTotal" @reduce="handleGetTotal"></cus-event-component>
    <cus-event-component1 @click.native="handleGetTotal1" @input.native="handleGetTotal1">
    </cus-event-component1>
    <p>事件:{{ eventMessage }}</p>
</div>
<!-- 演示子组件改变父级组件的值 -->
<div id="cus_event_component2">
    <p>总数:{{total}}</p>
    <cus-event-component2 v-model="total"></cus-event-component2>

</div>
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script>
    Vue.component('cus-event-component2', {
        template: '<button @click="handleClick">+1</button>',
        data:function (){
            return {
                counter:0
            }
        },
        methods:{
            handleClick:function (){
                this.counter++;
                this.$emit('input',this.counter)
            }
        }
    })

    new Vue({
        el:'#cus_event_component2',
        data:{
            total:0
        }
    })

    Vue.component('cus-event-component1', {
        template: '<div>\
             <button>鼠标点击事件</button>\
            <input type="text" placeholder="输入事件">\
            </div>'
    })
    Vue.component('cus-event-component', {
        template: '<div>\
        <input v-model="counter"/>\
        <button @click="handleIncrease">+1</button>\
        <button @click="handleReduce">-1</button>\
            </div>',
        props: {
            count: {
                type: Number
            }
        },
        data: function () {
            return {
                // 父亲组件通过props将count参数传递给子组件
                counter: this.count
            }
        },
        methods: {
            handleIncrease: function () {
                this.counter++;
                this.$emit('increase', this.counter)
            },
            handleReduce: function () {
                this.counter--;
                // $emit将this.counter 传递给父组件
                this.$emit('reduce', this.counter)
            }
        }
    });
    new Vue({
        el: '#cus_event',
        data: {
            total: 0,
            eventMessage: ''
        },
        methods: {
            handleGetTotal: function (total) {
                if (total instanceof Event) {
                    this.total = total.target.value
                } else {
                    this.total = total
                }

            },
            handleGetTotal1: function (event) {
                console.log("handleGetTotal1")
                this.eventMessage = event.target
            }
        }
    })
</script>
</body>
</html>